﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels;
using WebApp.ViewModels.Manage;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Web.Core;
using WebApp.Common.Caching;
using WebApp.BLL.Basic;
using WebApp.BLL.Evaluate;

namespace kzjd.rycp.WebApp.Controllers
{
    public class PublicController : Controller
    {

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region Menu

        [ChildActionOnly]
        public ActionResult Menu()
        {
            IList<UserMenuModel> userMenuList = GetUserMenus();

            string activeMenu = "";
            string activeMenu2 = "";

            foreach (var item in userMenuList)
            {
                if (!string.IsNullOrEmpty(item.Menuurl) && Request.RawUrl.Contains(item.Menuurl.Replace("~", "")))
                {
                    activeMenu = item.Menuid;
                    break;
                }
                foreach (var child in item.ChildMenus)
                {
                    if (!string.IsNullOrEmpty(child.Menuurl) && Request.RawUrl.Contains(child.Menuurl.Replace("~", "")))
                    {
                        activeMenu = item.Menuid;
                        activeMenu2 = child.Menuid;
                        break;
                    }

                    if (child.ChildMenus.Count > 0)
                    {
                        if (this.checkChildActive(child.ChildMenus, Request.RawUrl))
                        {
                            activeMenu = item.Menuid;
                            activeMenu2 = child.Menuid;
                            break;
                        }
                    }
                }
            }

            ViewBag.ActiveMenu = activeMenu;
            ViewBag.ActiveMenu2 = activeMenu2;
            ViewBag.MenuList = userMenuList;

            return View();
        }

        private bool checkChildActive(IList<UserMenuModel> menulist, string rawUrl)
        {
            foreach (var menu in menulist)
            {
                if (!string.IsNullOrEmpty(menu.Menuurl) && rawUrl.Contains(menu.Menuurl.Replace("~", "")))
                {
                    return true;
                }
                if (menu.ChildMenus.Count > 0)
                {
                    return this.checkChildActive(menu.ChildMenus, rawUrl);
                }
            }

            return false;
        }

        [NonAction]
        private IList<UserMenuModel> GetUserMenus()
        {
            IList<UserMenuModel> userMenuList = null;
            if (SessionManage.User == null)
            {
                userMenuList = new List<UserMenuModel>();
            }
            else
            {
                userMenuList = UserCache.GetUsermenus(SessionManage.User);
            }

            return userMenuList;
        }

        #endregion

        #region Header

        [ChildActionOnly]
        public ActionResult Header()
        {
            return View();
        }

        [ChildActionOnly]
        public ActionResult Usernav()
        {
            return View();
        }

        #endregion

        #region Footer

        [ChildActionOnly]
        public ActionResult Footer()
        {
            return View();
        }

        #endregion

        #region 获取提醒消息

        [IgnoreAuthorizeFilter]
        public JsonResult GetMessager()
        {
            try
            {
                var list = new List<MenuMessager>();

                ////探伤待审核
                //if (UserAuthBLL.HasAuth("Detection.Check"))
                //{
                //    string key = "Detection.Check.Alert";
                //    //6秒缓存
                //    int count = new MemoryCacheManager().Get<int>(key, 0.1, () =>
                //    {
                //        return new DetectiondataService().GetAlertCount();

                //    });
                //    if (count > 0)
                //    {
                //        list.Add(new MenuMessager
                //        {
                //            Message = "待审核的探伤记录",
                //            MsgCount = count,
                //            Url = "/Detection/Check"
                //        });
                //    }
                //}

                var result = new AjaxResult(AjaxResult.RESULT_OK, "");
                result.Content = list;
                return Json(result);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region SetLanguage

        [IgnoreAuthorizeFilter]
        public JsonResult SetLanguage(string lang)
        {
            SessionManage.Language = lang;

            S_user user = new S_userService().Find(SessionManage.User.Id);
            if (user != null)
            {
                new S_userService().Update(user);

                UserCache.InitUsreCache(SessionManage.User);
            }

            HttpCookie usercookie = new System.Web.HttpCookie("User");
            usercookie.Expires = DateTime.Now.AddMonths(1);
            Response.Cookies.Add(usercookie);

            return Json(new AjaxResult(AjaxResult.RESULT_OK, ""));
        }

        #endregion

        #region 上传文件

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">上传文件保存的子目录</param>
        /// <param name="allowex">允许的文件类型</param>
        /// <returns></returns>
        [IgnoreAuthorizeFilter]
        public JsonResult UploadFile(string path, string allowex)
        {
            string uploadroot = "~/Upload/";
            uploadroot = Server.MapPath(uploadroot);

            //文件上传失败
            UploadResult result = new UploadResult();
            try
            {
                //已客户代码建立子文件夹
                //uploadroot += SessionManage.Custcode + "\\";

                if (string.IsNullOrEmpty(path))
                {
                    //如果未指定文件子目录，则按照日期自动创建一个子目录
                    path = DateTime.Now.ToString("yyyyMMdd");
                }

                if (Request.Files.Count == 0)
                {
                    result.Ret = UploadResult.RESULT_ERROR;
                    result.Msg = CSMSLang.Get("message_choose_file");//"请选择文件！";
                    return Json(result);
                }

                //获取上传文件
                HttpPostedFileBase hpfFile = Request.Files[0];

                FileInfo fi = new FileInfo(hpfFile.FileName);
                //允许的文件类型
                if (!string.IsNullOrEmpty(allowex) && !"*".Equals(allowex))
                {
                    if (!allowex.EndsWith(",")) allowex += ',';
                    if (!allowex.ToLower().Contains(fi.Extension.ToLower() + ","))
                    {
                        result.Ret = UploadResult.RESULT_ERROR;
                        //result.Msg = "只能上传以下类型文件：" + allowex + "！";
                        result.Msg = CSMSLang.Get("public_upload_following") + "：" + allowex + "！";
                        return Json(result);
                    }
                }

                //上传文件名
                string serverfilename = Guid.NewGuid().ToString().Replace("-", "") + fi.Extension;

                //文件虚拟目录
                string filepath = path.TrimEnd('/') + "/";

                //文件物理目录
                string phfilepath = uploadroot + filepath;// Server.MapPath(filepath);
                //文件物理目录
                if (!Directory.Exists(phfilepath))
                {
                    Directory.CreateDirectory(phfilepath);
                }
                filepath = "/Upload/" + filepath;
                //保存文件
                hpfFile.SaveAs(phfilepath + serverfilename);
                //文件上传成功
                result.Ret = UploadResult.RESULT_OK;
                //文件虚拟路径（URL）
                result.Fileurl = filepath + serverfilename;
                //原始文件物理路径
                result.Filename = hpfFile.FileName;
                return Json(result);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                result.Ret = UploadResult.RESULT_ERROR;
                result.Msg = ex.Message;
                return Json(result);
            }
        }

        #endregion

        #region 根据身份证号获取出生日期

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">用户ID</param>
        [IgnoreAuthorizeFilter]
        public JsonResult CheckCardno(string cardno, string birthday)
        {
            AjaxResult result = new AjaxResult(AjaxResult.RESULT_OK, "");

            try
            {
                if (!string.IsNullOrEmpty(cardno))
                {
                    DateTime? date2 = CommonStr.GetCardBirthday(cardno);
                    if (date2.HasValue)
                    {
                        if (string.IsNullOrEmpty(birthday))
                        {
                            result = new AjaxResult(AjaxResult.RESULT_OK, "", date2.Value.ToString("yyyy-MM-dd"));
                        }
                        else
                        {
                            DateTime? date1 = CommonStr.TryGetdate(birthday);
                            if (!date1.Equals(date2))
                            {
                                result = new AjaxResult(AjaxResult.RESULT_ERROR, CSMSLang.Get("message_does_not_match"));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                result = new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message);
            }

            return Json(result);
        }

        #endregion

        #region 列设置

        [IgnoreAuthorizeFilter]
        public ActionResult ColumnSetting()
        {
            var pagekey = Request.QueryString["pagekey"];

            ViewBag.Pagekey = pagekey;

            var service = new S_gridcolumnService();

            //用户设置的列
            var usercollist = service.ListByPagekey(pagekey, SessionManage.User.Id);
            var fieldlist = usercollist.Select(p => p.Field).ToList();

            //可选的列
            var collist = service.ListByPagekey(pagekey, 0).Where(p => !fieldlist.Contains(p.Field)).ToList();

            ViewBag.UserCols = Newtonsoft.Json.JsonConvert.SerializeObject(usercollist.Select(p => new
            {
                p.Field,
                p.Title
            }).ToList());
            ViewBag.Cols = Newtonsoft.Json.JsonConvert.SerializeObject(collist.Select(p => new
            {
                p.Field,
                p.Title
            }).ToList());

            return View();
        }

        [IgnoreAuthorizeFilter]
        public JsonResult SaveUserColumn(string pagekey, string json)
        {
            try
            {
                var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<S_gridcolumn>>(json);

                new S_gridcolumnService().SaveList(pagekey, SessionManage.User.Id, list);

                return Json(new AjaxResult(AjaxResult.RESULT_OK, ""));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region GetResKey

        [IgnoreAuthorizeFilter]
        public string GetResKey(string name)
        {
            return new S_lang_resService().GetReskeyByName(name);
        }

        #endregion

        #region 测评年度选择

        [IgnoreAuthorizeFilter]
        public ActionResult EvalSelect()
        {
            return View();
        }

        [IgnoreAuthorizeFilter]
        public JsonResult EvalListJson(int page, int rows, string sort, string order)
        {
            var service = new T_evaluateService();

            Dictionary<string, object> result = new Dictionary<string, object>();

            int rowscount = 0;

            var list = service.PageList(page, rows, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.EvaluateYear,
                EvaluateStart = CommonStr.GetDateStr(p.EvaluateStart),
                EvaluateEnd = CommonStr.GetDateStr(p.EvaluateEnd),
                Status = ((enmEvalStatus)p.Status).ToString(),
                p.Remark
            });

            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        #endregion

    }
}